<template>
  <div>
    <div class="address-head">
      <div>
        <a-input v-model:value="searchCity"></a-input>
      </div>
      <div>
        <a-button type="primary" @click="openAddModal">新增</a-button>
      </div>
    </div>
    <a-tree :tree-data="treeData" :field-names="fieldNames" :blockNode="true">
      <template #title="item">
        <div style="display: flex; justify-content: space-between">
          <div>
            {{ item.areaName }}
          </div>
          <div style="display: flex; color: deepskyblue">
            <div
              style="margin: 0 15px"
              @click.stop="openEditModal(item.areaId)"
            >
              <edit-outlined />
              修改
            </div>
            <div>
              <a-popconfirm
                title="是否要删除?"
                ok-text="确认"
                cancel-text="取消"
                @confirm="confirmDeleted(item)"
              >
                <delete-outlined />
                删除
              </a-popconfirm>
            </div>
          </div>
        </div>
      </template>
    </a-tree>
    <a-modal
      v-model:visible="editVisible"
      title="修改"
      :footer="null"
      :maskClosable="false"
      :afterClose="resetForm"
    >
      <a-form
        ref="editFormRef"
        :model="addressFormState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="地区名称"
          name="areaName"
          :rules="[{ required: true, message: '地区名称不能为空' }]"
        >
          <a-input v-model:value="addressFormState.areaName" />
        </a-form-item>

        <a-form-item label="上级地区" name="parentIds">
          <a-cascader
            v-model:value="parentIds"
            :options="treeData"
            :field-names="{
              label: 'areaName',
              value: 'areaId',
              children: 'children',
            }"
            placeholder="请选择上级地区"
            :changeOnSelect="true"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" @click="editArea" html-type="submit"
            >确定
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="addVisible"
      title="新增"
      :footer="null"
      :maskClosable="false"
      :after-close="resetForm"
    >
      <a-form
        ref="formRef"
        :model="addressFormState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="地区名称"
          name="areaName"
          :rules="[{ required: true, message: '地区名称不能为空' }]"
        >
          <a-input v-model:value="addressFormState.areaName" />
        </a-form-item>

        <a-form-item label="上级地区" name="parentIds">
          <a-cascader
            v-model:value="parentIds"
            :options="treeData"
            :field-names="{
              label: 'areaName',
              value: 'areaId',
              children: 'children',
            }"
            placeholder="请选择上级地区"
            :changeOnSelect="true"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" @click="addArea" html-type="submit"
            >确定
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { Client } from "@/api/clientApi";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons-vue";
import { message, type FormInstance, type TreeProps } from "ant-design-vue";
import "ant-design-vue/es/message/style/css";
import { onMounted, reactive, ref } from "vue";

const treeData = reactive<any[]>([]);
const fieldNames = { title: "areaName", key: "areaId", children: "children" };
type itemType = Exclude<TreeProps["treeData"], undefined>[0];
const formRef = ref<FormInstance>();

// 确认删除节点
const confirmDeleted = (item: any) => {
  Client.adminArea.deleteAdminArea(item.areaId).then(() => {
    message.success("删除成功");
    loadTree();
  });
};
onMounted(() => {
  loadTree();
});

/**
 * 加载树信息
 */
const loadTree = async () => {
  treeData.length = 0;
  const cityList = await Client.adminArea.listUsingGet();
  treeData.push(...cityList);
};

// 搜索内容
const searchCity = ref<string>();

// 弹出层
const addVisible = ref<boolean>(false);

/**
 * 打开弹窗
 */
const openAddModal = () => {
  resetForm();
  addVisible.value = true;
};
const parentIds = ref<number[]>([]);
const addressFormState = reactive({
  areaId: 0,
  areaName: "",
  level: 0,
  parentId: 0,
});

/**
 * 新增地区
 */
const addArea = () => {
  formRef.value
    ?.validate()
    .then((res) => {
      addressFormState.level = parentIds.value.length + 1;
      if (parentIds.value.length > 0) {
        addressFormState.parentId = parentIds.value[parentIds.value.length - 1];
      }
      console.log(addressFormState);
      // 新增地区
      Client.adminArea.postAdminArea(addressFormState).then(() => {
        loadTree();
        message.success("添加成功");
        addVisible.value = false;
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

/**
 * 打开修改弹窗
 */
const editVisible = ref<boolean>(false);
const editFormRef = ref<FormInstance>();
const openEditModal = async (id: number) => {
  resetForm();
  const area = await Client.adminArea.getAdminArea(id);
  addressFormState.areaId = area.areaId;
  addressFormState.areaName = area.areaName;
  addressFormState.level = area.level;
  addressFormState.parentId = area.parentId;
  editVisible.value = true;
};
const editArea = () => {
  editFormRef.value
    ?.validate()
    .then((res) => {
      const len = parentIds.value.length;
      addressFormState.level = len + 1;
      if (len > 0 && addressFormState.areaId === parentIds.value[len - 1]) {
        message.error("不能设置当前地区为父节点");
        return;
      }
      if (len === 0) {
        addressFormState.parentId = 0;
      } else {
        addressFormState.parentId = parentIds.value[len - 1];
      }
      // 修改地区信息
      Client.adminArea.putAdminArea(addressFormState).then(() => {
        loadTree();
        message.success("修改成功");
      });
      editVisible.value = false;
    })
    .catch((err) => {
      console.log(err);
    });
};

/**
 * 重置表单
 */
const resetForm = () => {
  addressFormState.areaName = "";
  addressFormState.areaId = 0;
  addressFormState.level = 0;
  addressFormState.parentId = 0;
  parentIds.value = [];
};
</script>

<style>
.address-head {
  display: flex;
  justify-content: space-between;
}
</style>
